import React from 'react';
import {Table} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {Link} from 'react-router-dom';
import {hasPermissions} from './utils';
import {conventEnumValueToString, formatDateTime, formatAmount} from '../utils';
import {PERMISSION, formatExportExcelUrl, formatExportPdfUrl} from './constants';
import DropdownMenu from 'Shared/components/DropdownMenu';
import {TABLE, PAGINATION_OPTIONS, COMMON_TABLE_QUERY_FAIL_TEXT, COMMON_TABLE_EMPTY_TEXT, FIXED_COLUMN_WIDTH, DATE_FORMAT} from '../constants';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import {saleOrderTransportType, saleOrderPriceTerms, currency, paymentType, pIProformaInvoiceStatus, proformaInvoiceSource} from '../Enum';
import {abandonData} from './api';
const basePath = fetch.basePath || '';
const url = '/#/dcs/sales/CBUSaleOrder/add';
export class TablePanel extends React.PureComponent {
    constructor(props) {
        super(props);
        this.onChangeSort = this.onChangeSort.bind(this);
        this.state = {
            loading: false
        };
    }
    onChangeSort = (pagination, filters, sorter) => {
        this.props.onChangeSort({
            pageIndex: pagination.current - 1,
            pageSize: pagination.pageSize,
            sortedColumnKey: sorter.columnKey,
            sortedOrder: sorter.order,
        });
    };
    onClickAbandonBtn = id => {
        this.setState({loading: true});
        const record = this.props.data.find(d => d.id === id);
        abandonData(id, {rowVersion: record.rowVersion})
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.refreshListData();
            });
    }
    onExportExcel = e => {
        e.stopPropagation();
        window.open(formatExportExcelUrl(e.currentTarget.dataset.id, e.currentTarget.dataset.code));
    }
    onExportPdf = e => {
        e.stopPropagation();
        window.open(formatExportPdfUrl(e.currentTarget.dataset.id, e.currentTarget.dataset.code));
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {pageIndex, pageSize, total} = this.props;
        const locale = {
            emptyText: this.props.hasError ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
        };
        const pagination = {
            total,
            pageSize,
            current: pageIndex + 1,
            ...PAGINATION_OPTIONS
        };
        const columns = [{
            title: formatMessage({
                id: 'tablePanel.column.code',
                defaultMessage: 'PI编号'
            }),
            dataIndex: 'code',
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'code' && this.props.sortedOrder,
            render: (text, record) => <Link to={routes.detail.format(record.id)}>{record.code}</Link>
        }, {
            title: formatMessage({
                id: 'tablePanel.column.country',
                defaultMessage: '国家'
            }),
            dataIndex: 'country',
        }, {
            title: formatMessage({
                id: 'tablePanel.column.marketDepartmentName',
                defaultMessage: '大区'
            }),
            dataIndex: 'marketDepartmentName',
        }, {
            title: formatMessage({
                id: 'tablePanel.column.countryOfOrigin',
                defaultMessage: '原产国'
            }),
            dataIndex: 'countryOfOrigin',
        }, {
            title: formatMessage({
                id: 'tablePanel.column.countryOfDestination',
                defaultMessage: '目的国'
            }),
            dataIndex: 'countryOfDestination',
        }, {
            title: formatMessage({
                id: 'tablePanel.column.deliveryTerms',
                defaultMessage: '运输方式'
            }),
            dataIndex: 'deliveryTerms',
            render: text => conventEnumValueToString(saleOrderTransportType, text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.dataSource',
                defaultMessage: '数据来源'
            }),
            dataIndex: 'dataSource',
            render: text => conventEnumValueToString(proformaInvoiceSource, text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.tradeMethodName',
                defaultMessage: '贸易方式'
            }),
            dataIndex: 'tradeMethodName',
        }, {
            title: formatMessage({
                id: 'tablePanel.column.salesOrderPriceTerms',
                defaultMessage: '价格条款'
            }),
            dataIndex: 'salesOrderPriceTerms',
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'salesOrderPriceTerms' && this.props.sortedOrder,
            render: text => conventEnumValueToString(saleOrderPriceTerms, text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.paymentType',
                defaultMessage: '付款方式'
            }),
            dataIndex: 'paymentType',
            render: text => conventEnumValueToString(paymentType, text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.carrierName',
                defaultMessage: '货代名称'
            }),
            dataIndex: 'carrierName',
        }, {
            title: formatMessage({
                id: 'tablePanel.column.totalAmount',
                defaultMessage: 'PI金额'
            }),
            dataIndex: 'totalAmount',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.productAmount',
                defaultMessage: '清单总额'
            }),
            dataIndex: 'productAmount',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.shipmentAmount',
                defaultMessage: '运费汇总'
            }),
            dataIndex: 'shipmentAmount',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.insuranceAmount',
                defaultMessage: '保费汇总'
            }),
            dataIndex: 'insuranceAmount',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.currency',
                defaultMessage: '币种'
            }),
            dataIndex: 'currency',
            render: text => conventEnumValueToString(currency, text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.batchNumber',
                defaultMessage: '批次号'
            }),
            dataIndex: 'batchNumber',
        }, {
            title: formatMessage({
                id: 'tablePanel.column.createTime',
                defaultMessage: '提报日期'
            }),
            dataIndex: 'createTime',
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'createTime' && this.props.sortedOrder,
            render: text => formatDateTime(text, DATE_FORMAT)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.confirmTime',
                defaultMessage: '确认时间'
            }),
            dataIndex: 'confirmTime',
            render: text => formatDateTime(text, DATE_FORMAT)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.status',
                defaultMessage: '状态'
            }),
            dataIndex: 'status',
            render: text => conventEnumValueToString(pIProformaInvoiceStatus, text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.creatorName',
                defaultMessage: '创建人'
            }),
            dataIndex: 'creatorName',
        }, {
            title: formatMessage({
                id: 'tablePanel.column.operate',
                defaultMessage: '操作'
            }),
            dataIndex: 'operate',
            width: FIXED_COLUMN_WIDTH,
            fixed: 'right',
            render: (t, r) => {
                const menus = [
                    {
                        id: PERMISSION.update,
                        children: (
                            <Link key="update" to={routes.update.format(r.id)}>
                                {this.props.intl.formatMessage({
                                    id: 'tablePanel.operation.update',
                                    defaultMessage: '修改'
                                })}
                            </Link>
                        ),
                        hidden: !(hasPermissions(this.props.permissions, PERMISSION.update) && hasPermissions(r.options, PERMISSION.update))
                    },
                    {
                        id: PERMISSION.confirm,
                        children: (
                            <Link key="confirm" to={routes.confirm.format(r.id)}>{
                                this.props.intl.formatMessage({
                                    id: 'tablePanel.operation.confirm',
                                    defaultMessage: '确认'
                                })
                            }</Link>
                        ),
                        hidden: !(hasPermissions(this.props.permissions, PERMISSION.confirm) && hasPermissions(r.options, PERMISSION.confirm)),
                    },
                    {
                        id: PERMISSION.abandon,
                        children: (ref =>
                            <WrappedPopconfirm
                                key="abandon"
                                placement="topLeft"
                                onConfirm={this.onClickAbandonBtn}
                                onVisibleChange={ref.setMenuVisible}
                                id={r.id}
                                title={this.props.intl.formatMessage({
                                    id: 'tablePanel.validate.abandon',
                                    defaultMessage: '是否确认作废？'
                                })}>
                                <a>{
                                    this.props.intl.formatMessage({
                                        id: 'tablePanel.abandon',
                                        defaultMessage: '作废'
                                    })
                                }</a>
                            </WrappedPopconfirm>
                        ),
                        hidden: !(hasPermissions(this.props.permissions, PERMISSION.abandon) && hasPermissions(r.options, PERMISSION.abandon)),
                    },
                    {
                        id: PERMISSION.exportExcel,
                        children: (
                            <a key="exportExcel" data-id={r.id} data-code={r.code} onClick={this.onExportExcel}>
                                {this.props.intl.formatMessage({
                                    id: 'tablePanel.operation.exportExcel',
                                    defaultMessage: '导出Excel'
                                })}
                            </a>
                        ),
                        hidden: !hasPermissions(this.props.permissions, PERMISSION.exportExcel)
                    }, {
                        id: PERMISSION.exportPdf,
                        children: (
                            <a key="exportPdf" data-id={r.id} data-code={r.code} onClick={this.onExportPdf}>
                                {this.props.intl.formatMessage({
                                    id: 'tablePanel.operation.exportPdf',
                                    defaultMessage: '导出PDF'
                                })}
                            </a>
                        ),
                        hidden: !hasPermissions(this.props.permissions, PERMISSION.exportPdf)
                    }, {
                        id: PERMISSION.create,
                        children: <a href={`${basePath}${url}?piId=${r.id}`} target="_blank" rel="noopener noreferrer">{
                            this.props.intl.formatMessage({
                                id: 'tablePanel.operation.create',
                                defaultMessage: '生成销售订单'
                            })
                        }</a>,
                        hidden: !(hasPermissions(this.props.permissions, PERMISSION.create) && hasPermissions(r.options, PERMISSION.create) && (r.dataSource === 3)),
                    }];
                return <DropdownMenu key={r.id} menus={menus} primaryLength={1} id={r.id} />;
            }
        }];
        if(!this.props.isDealerUser)
            columns.splice(1, 0,
                {
                    title: this.props.intl.formatMessage({
                        id: 'historyTablePanel.column.dealerCode',
                        defaultMessage: '总代编号'
                    }),
                    sorter: true,
                    sortOrder: this.props.sortedColumnKey === 'dealerCode' && this.props.sortedOrder,
                    dataIndex: 'dealerCode',
                });
        return (
            <Table
                className={'white-space-nowrap'}
                columns={columns}
                dataSource={this.props.data}
                loading={this.props.loading || this.state.loading}
                onChange={this.onChangeSort}
                pagination={pagination}
                rowKey="id"
                locale={locale}
                {...TABLE}/>
        );
    }
}
TablePanel.propTypes = {
    data: PropTypes.array.isRequired,
    hasError: PropTypes.string.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    total: PropTypes.number.isRequired,
    onChangeSort: PropTypes.func.isRequired,
    intl: PropTypes.object,
    pageIndex: PropTypes.number,
    pageSize: PropTypes.number,
    sortedColumnKey: PropTypes.string,
    sortedOrder: PropTypes.string,
};
import {connect} from 'react-redux';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {tableSearch} from './actions';
import {injectIntl} from './intl';

const getData = selectorFactory(['page', 'domainData', 'list', 'data']);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const getIsDealerUser = selectorFactory(['page', 'domainData', 'initData', 'isDealerUser']);
const mapStateToProps = state => ({
    data: getData(state),
    isDealerUser: getIsDealerUser(state),
    loading: state.getIn(['page', 'domainData', 'list', 'isFetching']),
    hasError: state.getIn(['page', 'domainData', 'list', 'message']),
    total: state.getIn(['page', 'domainData', 'list', 'total']),
    pageIndex: state.getIn(['page', 'appState', 'queryBySort', 'pageIndex']),
    pageSize: state.getIn(['page', 'appState', 'queryBySort', 'pageSize']),
    sortedColumnKey: state.getIn(['page', 'appState', 'queryBySort', 'sortedColumnKey']),
    sortedOrder: state.getIn(['page', 'appState', 'queryBySort', 'sortedOrder']),
    permissions: getPermissions(state),
});

const mapDispatchToProps = dispatch => ({
    onChangeSort: option => dispatch(tableSearch(option)),
    refreshListData: () => dispatch(tableSearch())
});

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(TablePanel));


